package edu.osumc.bmi.restful.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import edu.osumc.bmi.restful.schema.User;
import edu.osumc.bmi.restful.service.RestfulService;
import edu.osumc.bmi.restful.util.RestfulException;

@Controller
@RequestMapping("/httpResponseUser")
public class HttpResponseUserController {
	@Autowired
	@Qualifier("restfulService")
	private RestfulService restfulService;

	@RequestMapping(method = RequestMethod.GET, value = "/")
	@ResponseBody
	public List<User> getAllUsers() {
		return restfulService.getAllUsers();
	}

	@RequestMapping(method = RequestMethod.GET, value = "/{userId}")
	@ResponseBody
	public User getUser(@PathVariable("userId") Integer id)
			throws RestfulException {
		User user = restfulService.getUser(id);
		return user;
	}

	@RequestMapping(method = RequestMethod.POST, value = "/{userId}/{firstName}/{lastName}/{loginId}")
	public String addUser(@PathVariable("userId") Integer id,
			@PathVariable String firstName, @PathVariable String lastName,
			@PathVariable String loginId) throws RestfulException {
		User user = new User();
		user.setId(id);
		user.setFirstName(firstName);
		user.setLastName(lastName);
		user.setLoginId(loginId);
		restfulService.addUser(user);
		return "redirect:/httpResponseUser/" + id;
	}

	@RequestMapping(method = RequestMethod.DELETE, value = "/{userId}")
	@ResponseBody
	public String deleteUser(@PathVariable("userId") Integer id) throws RestfulException {
		restfulService.deleteUser(id);
		return "OK";
	}

	@RequestMapping(method = RequestMethod.PUT, value = "/{userId}/{firstName}/{lastName}/{loginId}")
	public String updateUser(@PathVariable("userId") Integer id,
			@PathVariable String firstName, @PathVariable String lastName,
			@PathVariable String loginId) throws RestfulException {
		User user = restfulService.getUser(id);
		user.setFirstName(firstName);
		user.setLastName(lastName);
		user.setLoginId(loginId);
		restfulService.updateUser(user);
		return "redirect:/httpResponseUser/" + id;
	}
}
